/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.utils;

import java.util.Collection;
import java.util.concurrent.ThreadPoolExecutor;

import com.cqcis.uip.base.framework.core.LogService;
import com.cqcis.uip.base.framework.core.RegisteredService;
import com.cqcis.uip.base.logadaptor.LogConfiguration;

/**
 * 服务日志工具, 向服务中增加日志和删除日志
 * 
 * @author huangmy
 * @date   2008-4-12
 */
public class RegisterServiceLogUtil {
	/**
	 * 添加日志配置到服务中
	 * 
	 * @param rs
	 * @param config 要增加的配置实例
	 */
    public static void addLogToRS(RegisteredService rs, LogConfiguration config) {
    	LogConfiguration configRS = rs.getLogConfiguration();
    	LogService logService = rs.getRegisteredServiceContext().getLogService();// 日志服务    	
    	Collection<ThreadPoolExecutor> tpes = LogConfigurationUtil.getTPEsFor(configRS);
    	if (tpes != null) {
    		for (ThreadPoolExecutor tpe : tpes) {
    			Collection<Thread> threads = LogServiceThreadPoolExecutor.getAllActiveThreadsFrom(tpe);
    			if (threads != null) {    				
    				for (Thread thread : threads) {    					
    					logService.register(config, thread); // 实时注册, 运行态线程
    				}
    			}
    		}
    	}
    	
    	// 延迟注册, 适用于新建线程
    	configRS.addRelationConfig(config);
    }
    
    /**
     * 从服务删除日志配置
     * 
     * @param rs
     * @param config 要删除的配置实例
     */
    public static void removeLogToRS(RegisteredService rs, LogConfiguration config) {
    	config.destroy(); // 销毁
    	
    	// 清理注册服务日志配置
    	LogConfiguration configRS = rs.getLogConfiguration();
    	if (configRS != null) {
    		configRS.removeRelationConfig(config);    		
    	}
    	
    	LogService logService = rs.getRegisteredServiceContext().getLogService();// 日志服务
    	
    	// 清理存活线程日志    	
    	Collection<ThreadPoolExecutor> tpes = LogConfigurationUtil.getTPEsFor(configRS);
		if (tpes != null) {
    		for (ThreadPoolExecutor tpe :tpes) {        			
    			Collection<Thread> threads = LogServiceThreadPoolExecutor.getAllActiveThreadsFrom(tpe);
    			if (threads != null) {
    				for (Thread thread : threads) {
    					logService.removeLogConfiguration(config, thread);
    					logService.tryCloseLogAppender(config);
    					
    					// 清除关联的配置
    					Collection<LogConfiguration> relaConfigs = config.getAllRelationConfigs();
    					if (relaConfigs != null) {
    						for (LogConfiguration relaConfig : relaConfigs) {
    							logService.removeLogConfiguration(relaConfig, thread);
            					logService.tryCloseLogAppender(relaConfig);
    						}
    					}
    				}
    			}
    		}
    	}
    	
    	logService.tryCloseLogAppender(config);
    }
}
